package com.okonna.selenium.tide.eventhandlers.genericevents;

import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Text;

import com.okonna.selenium.tide.Application;
import com.okonna.selenium.tide.managers.RCManager;

public class RunDumpTextListener implements SelectionListener
{
	private Text txtURL, txtTarget, txtResult, txtWaitTime;
	private Button btnWait;
	private String strResult;
	private Application app;
	private Display display;
	private RCManager selRCManager;
	
	public RunDumpTextListener(Application tmpApp, Text tmpURL, Text tmpTarget, Text tmpResult, Button tmpWait, Text tmpWaitTime)
	{
		System.out.println(this.getClass().getSimpleName() + ".RunDumpTextListener(Alot)");
		app = tmpApp;
		display = app.getDisplay();
		selRCManager = app.getRCManager();
		txtURL = tmpURL;
		txtTarget = tmpTarget;
		btnWait = tmpWait;
		txtWaitTime = tmpWaitTime;
		txtResult = tmpResult;
	}

	@Override
	public void widgetSelected(SelectionEvent event) 
	{
		try
		{
		    selRCManager.openPage(txtURL.getText());
		    if (btnWait.getSelection())
		    {
				txtResult.setText("Waiting");
				txtResult.redraw();
				display.update();
				Thread.sleep(Integer.parseInt(txtWaitTime.getText()));
		    }
		    txtResult.setText("Working");
		    txtResult.redraw();
		    display.update();
		    strResult = selRCManager.dumpText(txtTarget.getText());
		    if (strResult.length() > 0 && strResult.length() <= 5000)
		    {
			    txtResult.setText(strResult);
			    txtResult.redraw();
		    }
		    else if (strResult.length() > 5000)
		    {
			    txtResult.setText("Overflow - Result was over 5000");
			    txtResult.redraw();
		    }
		    else
		    {
			    txtResult.setText("Blank result");
			    txtResult.redraw();
		    }
		    display.update();
		}
		catch (Exception e)
		{
		    System.out.println("\nException:\n" + e + "\n");
		}
	}

	@Override
	public void widgetDefaultSelected(SelectionEvent e) 
	{
		System.out.println("WTF does 'widgetDefaultSelected(SelectionEvent event)' do?");
	}
}
